package com.koron.common.web.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.bean.base.Response;
import com.koron.bean.query.PageQuery;
import com.koron.common.core.business.print.bean.PrintBusinessBean;
import com.koron.common.core.business.print.bean.PrintTemplateBean;
import com.koron.common.core.business.print.bean.dto.PrintTemplateDto;
import com.koron.common.core.business.print.printstandard.PrintStandardMapper;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CodeTools;
import com.koron.common.core.util.IpUtil;
import com.koron.common.core.util.StringUtils;
import com.koron.common.web.CommonWebApplication;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;


@Api(tags = "打印模板配置")
@Slf4j
@RestController
@RequestMapping("/printConfig")
public class PrintConfigController {

    private static String printHost;    //本地打印控件地址
    private static String printUrl;        //打印控件回调项目地址

    private String getCurrDs() {
        return ThreadLocalContext.get().getCurrDs();
    }


    @ApiOperation(value = "添加打印模板")
    @GetMapping("/addPrintTem.htm")
    @ResponseBody
    public Response<String> addPrintTem(PrintTemplateDto dto) {
        PrintTemplateBean bean = Convert.convert(PrintTemplateBean.class, dto);

        PrintBusinessBean businessbean = ADOConnection.runTask(getCurrDs(), factory -> {
            return factory.getMapper(PrintStandardMapper.class).queryFirstByBusinessCode(dto.getBusinessCode());
        }, PrintBusinessBean.class);

        Assert.isFalse(StringUtils.isNull(businessbean), "没有该打印业务");

        List<PrintTemplateBean> templatelist = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), factory -> {
            List<PrintTemplateBean> templateListByBusinessCode = factory.getMapper(PrintStandardMapper.class).getTemplateListByBusinessCode(dto.getBusinessCode());
            return templateListByBusinessCode;
        }, List.class);

        List<PrintTemplateBean> defaultlist = templatelist.stream().filter(a -> a.getDefaultFlag()).collect(Collectors.toList());
        Assert.isFalse(defaultlist.size() >= 1 && dto.getDefaultFlag(), "该业务已存在一个默认模板");

        ADOConnection.runTask(getCurrDs(), factory -> {
            bean.setId(CodeTools.getCode32());
            bean.setDeleteFlag(0);
            bean.setBusinessId(businessbean.getId());
            return factory.getMapper(PrintStandardMapper.class).insertInitTemplate(bean);
        }, Integer.class);

        return Response.ok("成功");
    }


    @ApiOperation(value = "删除模板")
    @DeleteMapping("/deletePrintTem.htm")
    @ResponseBody
    public Response<String> deletePrintTem(@RequestParam("id") String id) {
        ADOConnection.runTask(getCurrDs(), factory -> {
            Integer del = factory.getMapper(PrintStandardMapper.class).deletePrintTemByBusId(id);
            return del;
        }, Integer.class);
        return Response.ok("成功");
    }


    @ApiOperation(value = "修改模板")
    @GetMapping("/updataPrintTem.htm")
    @ResponseBody
    public Response<String> updataPrintTem(PrintTemplateDto dto) {

        PrintBusinessBean businessbean = ADOConnection.runTask(getCurrDs(), factory -> {
            return factory.getMapper(PrintStandardMapper.class).queryFirstByBusinessCode(dto.getBusinessCode());
        }, PrintBusinessBean.class);

        Assert.isFalse(StringUtils.isNull(businessbean), "没有该打印业务");

        List<PrintTemplateBean> templatelist = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), factory -> {
            List<PrintTemplateBean> templateListByBusinessCode = factory.getMapper(PrintStandardMapper.class).getTemplateListByBusinessCode(dto.getBusinessCode());
            return templateListByBusinessCode;
        }, List.class);

        List<PrintTemplateBean> defaultlist = templatelist.stream().filter(a -> a.getDefaultFlag() && !a.getId().equals(dto.getId())).collect(Collectors.toList());
        Assert.isFalse(defaultlist.size() >= 1 && dto.getDefaultFlag(), "该业务已存在一个默认模板");


        PrintTemplateBean bean = Convert.convert(PrintTemplateBean.class, dto);
        ADOConnection.runTask(getCurrDs(), factory -> {
            bean.setDeleteFlag(0);
            bean.setBusinessId(businessbean.getId());
            return factory.getMapper(PrintStandardMapper.class).updatePrintTem(bean);
        }, Integer.class);
        return Response.ok("成功", dto.getId());
    }


    @ApiOperation(value = "打印模板配置-列表")
    @GetMapping("/queryList")
    public Response<PageInfo> queryList(PageQuery query, @RequestParam("businessGroup") String businessGroup, @RequestParam(value = "name", required = false) String name) {
        PageHelper.startPage(query.getPage(), query.getPageSize(), query.getOrderBy());
        List<PrintTemplateDto> list = ADOConnection.runTask(getCurrDs(), factory -> {
            return factory.getMapper(PrintStandardMapper.class).queryAllByBusinessGroup(businessGroup, name);
        }, List.class);
        return Response.ok(new PageInfo(list));
    }


    @ApiOperation(value = "下载打印控件")
    @GetMapping("/downloadPrint")
    public void downloadPrint(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ApplicationHome ah = new ApplicationHome(CommonWebApplication.class);
        String docStorePath = ah.getSource().getParentFile().toString();//jar部署目录上级目录
        String printName = "AIOPrint.zip";
        File file = new File(docStorePath);
        File parentFile = file.getParentFile();
        String join = StrUtil.join("", parentFile.toString(), "\\", printName);
        log.debug("打印控件地址:{}", join);

        ServletOutputStream outputStream = null;
        try {
            // 创建输出流对象
            outputStream = response.getOutputStream();

            //以字节数组的形式读取文件
            byte[] bytes = FileUtil.readBytes(join);

            // 设置返回内容格式
            response.setContentType("application/octet-stream");

            // 把文件名按UTF-8取出并按ISO8859-1编码，保证弹出窗口中的文件名中文不乱码
            // 中文不要太多，最多支持17个中文，因为header有150个字节限制。
            // 这一步一定要在读取文件之后进行，否则文件名会乱码，找不到文件
            printName = new String(printName.getBytes("UTF-8"), "ISO8859-1");

            // 设置下载弹窗的文件名和格式（文件名要包括名字和文件格式）
            response.setHeader("Content-Disposition", "attachment;filename=" + printName);

            // 返回数据到输出流对象中
            outputStream.write(bytes);

            // 关闭流对象
            IoUtil.close(outputStream);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (outputStream != null) {
                IoUtil.close(outputStream);
            }
        }

    }

    @Deprecated
    @ApiOperation(value = "获取用户ip")
    @GetMapping("/getIp")
    public Response<String> getIp(HttpServletRequest request) {
        String ipAddr = IpUtil.getIpAddr(request);
        return Response.ok(ipAddr);
    }
}
